/**
 * 
 */
var throttle = function() {
    var isClear = arguments[0], fn;
    // 如果第一个参数是boolean类型那么第一个参数表示是否清楚计时器
    if (typeof isClear === 'boolean') {
        fn = arguments[1];
        fn.__throttleID && clearTimeout(fn.__throttleID);
    } else {
        fn = isClear;
        param = arguments[1];
        var p = extend({
            context: null,//函数执行作用域
            args: [],//函数执行相关参数
            time: 300//函数执行延迟时间
        }, param);
        arguments.callee(true, fn);
        fn.__throttleID = setTimeout(function() {
            fn.apply(p.context, p.args);
        }, p.time);
    }
}


// 外观模式封装元素方法
function $(id) { return document.getElementById(id); }
function $tag(tag, container) {
    container = container || document;
    return container.getElementsByTagName(tag);
}

var Layer = function(id) {
    this.container = $(id);
    this.layer = $tag('div', this.container)[0];

    this.lis = $tag('li', this.container);
    this.imgs = $tag('img', this.container);
    this.bindEvent();
}

Layer.prototype = {
    // 绑定交互事件，使用节流器延迟隐藏浮层30-5
    bindEvent: function() {
        var that = this;

        function hideLayer() {
            that.layer.className = '';
        }
        function showLayer() {
            that.layer.className = 'show';
        }

        // 鼠标光标移入事件
        that.on(that.container, 'mouseenter', function() {
            throttle(true, hideLayer);
            throttle(showLayer);
        }).on(that.container, 'mouseleave', function() {
            throttle(hideLayer);
            throttle(true, showLayer);
        });

        for(var i = 0; i < that.lis.length; i++) {
            that.lis[i].index = i;
            that.on(that.lis[i], 'mouseenter', function() {
                var index = this.index;
                for(var j = 0; j < that.imgs.length; j++) {
                    that.imgs[j].className = '';
                }

                that.imgs[index].className = 'show';
                that.layer.style.left = -22 + 60 * index + 'px';
            })
        }
    },
    // 事件绑定方法
    on: function(ele, type, fn) {
        ele.addEventListener ? ele.addEventListener(type, fn, false) : ele.attachEvent('on' + type, fn);
        return this;
    }
};
